package com.zhuangfei.hpuhelper.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.hpu.bean.Notice;
import com.hpu.constants.HttpConstants;
import com.hpu.constants.ShareConstants;
import com.hpu.parser.NoticeParser;
import com.hpu.service.LoginService;
import com.hpu.service.NoticeService;
import com.hpu.tools.ShareTools;
import com.zhuangfei.hpuhelper.tools.DefaultHandler;
import com.zhuangfei.hpuhelper.view.MyApplication;
import com.zhuangfei.hpuhelper.view.NoticeDetailActivity;
import com.zhuangfei.toolkit.model.BundleModel;
import com.zhuangfei.toolkit.tools.ActivityTools;

import cn.lzf.serviceplatform.R;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class SchoolNoticeFragment extends LazyLoadFragment {

    /**
     * Fragment用以复用的View
     */
    private View mView;

    private NoticeService noticeService;
    private LoginService loginService;

    SimpleAdapter simpleAdapter;
    List<Map<String, String>> items = new ArrayList<>();

    private ListView listView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_notice, container, false);
        return mView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        initView(mView);
        initEvent();
        super.onViewCreated(view, savedInstanceState);
    }

    private void initView(View view) {
        loginService = new LoginService(getActivity(), handler);
        noticeService = new NoticeService(handler, getActivity());

        // 刷新控件初始化
        listView = (ListView) mView.findViewById(R.id.id_tab02_listview);

        simpleAdapter = new SimpleAdapter(getActivity(), items, R.layout.item_notice_layout, new String[]{"order",
                "date", "title"},
                new int[]{R.id.id_message_item_order, R.id.id_message_item_date, R.id.id_message_item_title});
        listView.setAdapter(simpleAdapter);
    }

    /**
     * 初始化事件
     */
    private void initEvent() {
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                ActivityTools.toActivity(getActivity(), NoticeDetailActivity.class,
                        new BundleModel().put("id", items.get(arg2).get("id"))
                                .put("title", items.get(arg2).get("title"))
                                .setFromItem(1));
            }
        });
    }

    public void showMessage(List<Notice> notices) {
        items.clear();
        int m = 1;
        for (int i = notices.size() - 1; i >= 0; i--) {
            Notice notice = notices.get(i);
            Map<String, String> map = new HashMap<>();
            map.put("date", notice.getTime());
            map.put("id", notice.getId());
            map.put("title", notice.getName());
            map.put("order", m + "");
            m++;
            items.add(map);
        }
        simpleAdapter.notifyDataSetChanged();
    }

    DefaultHandler handler = new DefaultHandler(MyApplication.getInstance()) {
        public void handleMessage(Message msg) {
            getViewHelper().showSuccessView();
            super.handleMessage(msg);

            switch (msg.what) {
                case HttpConstants.QUERY_SCHOOL_NOTICE_SUCCESS:
                    NoticeParser noticeParser = new NoticeParser();
                    List<Notice> notices = noticeParser.parse(msg.obj.toString());
                    showMessage(notices);
                    break;

                // VPN过期，重新登录
                case HttpConstants.VPN_TOOLONG:
                    if(handler.isIgnoreVpnExpired()){
                        break;
                    }
                    getViewHelper().showLoadingView();
                    loginService.login(ShareTools.get(getActivity(), ShareConstants.STORE_USER, "").toString(),
                            ShareTools.get(getActivity(), ShareConstants.STORE_PASSWORD1, "").toString(),
                            ShareTools.get(getActivity(), ShareConstants.STORE_PASSWORD2, "").toString());
                    break;

                // 登录成功,重新获取
                case HttpConstants.LOGIN_SUCCESS:
                    ShareTools.put(getActivity(), ShareConstants.STORE_LOGINCOOKIE, (String) msg.obj);
                    lazyLoad();
                    break;
            }
        }

        ;
    };

    @Override
    protected void lazyLoad() {
        noticeService.getSchoolNotice();
    }
}
